package com.neusoft.training.podcast.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.neusoft.training.podcast.entity.Category;
import com.neusoft.training.podcast.entity.Comment;
import com.neusoft.training.podcast.entity.User;
import com.neusoft.training.podcast.entity.Video;
import com.neusoft.training.podcast.service.CategoryService;
import com.neusoft.training.podcast.service.CommentService;
import com.neusoft.training.podcast.service.UserService;
import com.neusoft.training.podcast.service.VideoService;
import com.neusoft.training.podcast.util.FileUploadTool;
import com.neusoft.training.podcast.util.TransfMediaTool;

@Controller
public class VideoController {
	
	@Autowired
	private VideoService videoService ;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private CategoryService categoryService;
	
	@RequestMapping("/videoList")
	public ModelAndView listVideos(ModelAndView mv) {
		List<Video> videos = videoService.findAllVideos();
		List<User> users = new ArrayList<User>();
		for(int i =0;i<videos.size();i++) {
			Integer authorID = videos.get(i).getAuthorID();
			User user = userService.findByID(authorID);
			users.add(user);
		}
		mv.addObject("videos", videos);
		mv.addObject("users",users);
		mv.setViewName("home");
		return mv;
	} 
	
	@RequestMapping("/showVideoList")
	public ModelAndView showVideos(ModelAndView mv) {
		List<Video> videos = videoService.findAllVideos();
		List<Category> categories = categoryService.findAllCategories();
		List<User> users = new ArrayList<User>();
		List<Category> types= new ArrayList<Category>();
		
		for(int i =0;i<videos.size();i++) {
			Integer authorID = videos.get(i).getAuthorID();
			User user = userService.findByID(authorID);
			users.add(user);
			
			Integer categoryID = videos.get(i).getCategoryID();
			Category category = categoryService.findCategoryName(categoryID);
			types.add(category);	
		}
		mv.addObject("categories",categories);
		mv.addObject("types",types);
		mv.addObject("users",users);
		mv.addObject("videos", videos);
		mv.setViewName("loginuser");
		return mv;
	}
	
	@RequestMapping("/showCategoryVideoList")
	public ModelAndView showMoviesVideos(ModelAndView mv,String categoryName) {
		
		List<Video> videos = videoService.showVideosByCategory(categoryName);
		List<String> userName = new ArrayList<String>();
		for(int i =0;i<videos.size();i++) {
			Integer authorID = videos.get(i).getAuthorID();
			User user = userService.findByID(authorID);
			userName.add(user.getName());
		}
		mv.addObject("videos", videos);
		mv.addObject("userName", userName);
		if("电影".equals(categoryName)) {
			mv.setViewName("movie");
		}else if("电视剧".equals(categoryName)) {
			mv.setViewName("TV");
		}else if("生活".equals(categoryName)) {
			mv.setViewName("life");
		}else if("新闻".equals(categoryName)) {
			mv.setViewName("news");
		}else if("综艺".equals(categoryName)) {
			mv.setViewName("play");
		}
		
		return mv;
	}
	
	@RequestMapping("/changeCover")
	public ModelAndView changeVideos(ModelAndView mv, HttpServletRequest request) {
		List<Video> videos = videoService.findAllVideos();
		
		for(int i=0; i<videos.size(); i++)
		{
			Video video = videos.get(i);
			String ffmpegPath = request.getServletContext().getRealPath("/tools/ffmpeg.exe");
			TransfMediaTool transfMediaTool = new TransfMediaTool();
			transfMediaTool.processFLV(ffmpegPath, video.getFilePath(), video.getFilePath());
			videoService.changeVideoCover(video);
					
		}
		mv.addObject("videos", videos);
		mv.setViewName("loginuser");
		return mv;
	} 
	
	@RequestMapping("/deleteVideo")
	public @ResponseBody List<Video> deleteVideo(String videoID){
		
		videoService.deleteVideo(videoID);
		
		List<Video> videos = videoService.findAllVideos();
		return videos;
		
	}
	
	@RequestMapping("/checkTitleExist")
	public @ResponseBody Map<String,String> checkTitleExist(String title) {
		List<Video> videos = videoService.findVideoByName(title);
		Map<String,String> result = new HashMap<String,String>();
		if(videos.size() == 0) {
			result.put("setNumber", "0");
			return result;
		}else {
			int max =0;
			int cur;
			for(int i=0;i<videos.size();i++) {
				String TVcategoryNumber = videos.get(0).getVideoID().substring(5, 7);
				cur = Integer.parseInt(TVcategoryNumber);
				if(max < cur)	max = cur;
			}
			result.put("setNumber",String.valueOf(max + 1));
			result.put("categoryID", String.valueOf(videos.get(0).getCategoryID()));
			
			return result;
		}
	}
	
	// 根据视频ID号播放相关视频
	@RequestMapping("/playVideo")
	public ModelAndView PlayVideo(String videoID,ModelAndView mv) {
		videoService.clickVideo(videoID);
		Video video = videoService.findVideoByID(videoID);
		String categoryName = categoryService.findCategoryByID(video.getCategoryID());
		List<Video> videos = videoService.findVideoOfAuthor(video.getAuthorID());
		List<Comment> comments = commentService.findCommendByVideoID(videoID);
		List<String> userName = new ArrayList<String>();
		/*获取评论的用户列表*/
		// 每条评论的用户ID
		Integer tempUserID = 0;
		List<User> commentUsers = new ArrayList<User>();
		for(int i=0; i<comments.size(); i++){
			tempUserID = comments.get(i).getCommentUserID();
			commentUsers.add(userService.findUserByID(tempUserID));
		}
		for(int i =0;i<videos.size();i++) {
			Integer authorID = videos.get(i).getAuthorID();
			User user = userService.findByID(authorID);
			userName.add(user.getName());
		}
		mv.addObject("userName", userName);
		mv.addObject("categoryName", categoryName);
		mv.addObject("commentUsers",commentUsers);
		mv.addObject("comments",comments);
		mv.addObject("video", video);
		mv.addObject("videos", videos);
		mv.setViewName("single");
		return mv;
	}
	
	// 根据视频ID号点赞视频
	@RequestMapping("/likeVideo")
	public String likeVideo(String videoID, String recommentCount) {
		
		videoService.likeVideo(videoID,Integer.parseInt(recommentCount));
		return "like_success";
	}
	
	// 根据视频ID号点赞视频
	@RequestMapping("/searchVideo")
	public ModelAndView searchVideo(String title,ModelAndView mv) {
		List<Video> allVideos = new ArrayList<Video>();
		List<Video> videos = videoService.findVideoByMName(title);
		List<User> users = userService.findUserByName(title);
		allVideos.addAll(videos);
		for(int i=0;i<users.size();i++) {
			List<Video> oneUserVideo = videoService.findVideoOfAuthor(users.get(i).getUserID());
			allVideos.addAll(oneUserVideo);
		}
		mv.addObject("videos", allVideos);
		mv.setViewName("search");
		return mv;
	}

	
	@RequestMapping("/uploadVideo")
	@ResponseBody
	public String uploadVideo(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, String title,
			String categoryID, String description, Integer setNumber, Integer userID) {
		String message = "";
		FileUploadTool fileUploadTool = new FileUploadTool();
		Video video = new Video();
		video.setTitle(title);
		video.setCategoryID(Integer.parseInt(categoryID));
		video.setDescription(description);
		
		//JSONObject getObj = new JSONObject();  
		try {
			video = fileUploadTool.createFile(multipartFile, request, video);
			String videoID = "";
			if(video != null){
				int categoryNumber = videoService.countCategoryVideos(video.getCategoryID());
				List<Video> videos = videoService.findVideoByName(title);
				
				if(videos.size() == 0) {
					videoID = String.format("%02d", video.getCategoryID())+ String.format("%03d", categoryNumber+1) + String.format("%02d", setNumber);
				}else {
					String TVcategoryNumber = videos.get(0).getVideoID().substring(0, 5);
					System.out.println(TVcategoryNumber);
					videoID = TVcategoryNumber + String.format("%02d", setNumber);
				}
				
				video.setVideoID(videoID);
				video.setAuthorID(userID);
				System.out.println(videoID);
				videoService.saveVideo(video);
				message = "上传成功";
			}else{
				message = "上传失败";
		}

		} catch (Exception e) {
			e.printStackTrace();
		}
			return message;
		}
	
}
